<?php

namespace app\common\model;

use fast\Tree;
use think\Db;
use think\Model;
use traits\model\SoftDelete;

class GoodsCategory extends Model
{

    use SoftDelete;

    

    // 表名
    protected $name = 'goods_category';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [
		'status_text'
    ];
    
    const STATUS_Y= 1;
    const STATUS_N = 0;
    
    public static $statusList = [
        self::STATUS_Y => '正常',
	    self::STATUS_N => '禁用'
    ];
    
    public function getStatusTextAttr($value, $data) {
    	$value = $value ? : $data['status'];
    	$list = self::$statusList;
    	return $list[$value] ?? '';
    }

    protected static function init()
    {
        self::afterInsert(function ($row) {
            $pk = $row->getPk();
            $row->getQuery()->where($pk, $row[$pk])->update(['sort' => $row[$pk]]);
        });
    }
	
	
	
	/**
	 * 获取上下级关系分类
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public function getTreeCategory(){
		$tree = Tree::instance();
		$tree->init(collection($this->order('sort desc,id desc')->select())->toArray(), 'parent_id');
		$categorys = $tree->getTreeList($tree->getTreeArray(0), 'name');
		return $categorys;
	}
	
	public function getListById($pid = 0){
		$where['parent_id'] = $pid;
		$where['status'] = self::STATUS_Y;
		$rows = Db::name('goodsCategory')
			->where($where)
			->where('delete_time', 'null')
			->order('sort ASC')->select();
		
		return $rows;
	}



}
